import React, {Component} from 'react';
import styles from './index.module.scss'
import MyNavBar from '../../components/MyNavBar'
import { WhiteSpace, WingBlank, Flex, Toast } from 'antd-mobile'
import { login } from '../../api/user'
import { setToken } from '../../utils/token'

class Login extends Component {
  constructor () {
    super()

    this.state = {
      username: 'test2',
      password: 'test2'
    }
  }

  changeValue = e => {
    this.setState({
      // 属性表达式，动态表示对象中的key值
      [e.target.name]: e.target.value
    })
  }

  userLogin = async () => {
    const res = await login(this.state)

    if (res.data.status === 400) {
      Toast.info(res.data.description, 1.5)
      return
    }

    Toast.info('登录成功', 1)

    // 1.token保存到本地
    setToken(res.data.body.token)
    // 2.有参数就返回来源页面，没有就返回上一页
    const { location } = this.props
    if (location.state && location.state.from) {
      // push的话页面数组就是[mine,login,rent]
      // replace的话页面数组就是[mine,rent]
      this.props.history.replace(location.state.from)
    } else {
      this.props.history.goBack()
    }
    
  }

  render () {
    const { username, password } = this.state
    return (
      <div className={styles.root}>
        <MyNavBar>账号登录</MyNavBar>
        <WhiteSpace size='xl' />
        <WingBlank size='lg'>
          <div className={styles.formItem}>
            <input
              type="text"
              className={styles.input}
              value={username}
              name='username'
              onChange={this.changeValue}
              placeholder='请输入账号'/>
          </div>
          <div className={styles.formItem}>
            <input
              type="password"
              className={styles.input}
              value={password}
              name='password'
              onChange={this.changeValue}
              placeholder='请输入密码'/>
          </div>
          <div className={styles.formSubmit}>
            <div onClick={this.userLogin} className={styles.submit}>登录</div>
          </div>
          <Flex className={styles.backHome}>
            <Flex.Item>
              <a href="#/">还没有账号，去注册</a>
            </Flex.Item>
          </Flex>
        </WingBlank>
      </div>
    )
  }
}

export default Login;